package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

import static org.springframework.beans.BeanUtils.copyProperties;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Override
    public void save(DishDTO dishDTO) {
        Dish dish = new Dish();
        copyProperties(dishDTO, dish);
        dish.setStatus(StatusConstant.DISABLE);
        dishMapper.insert(dish);
    }

    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        List<DishVO> rows = dishMapper.pageQuery(dishPageQueryDTO);
        Page<DishVO> p = (Page<DishVO>) rows;
        return new PageResult(p.getTotal(), p.getResult());
    }

    @Override
    public void update(DishDTO dishDTO) {
        Dish dish = new Dish();
        copyProperties(dishDTO, dish);
        dishMapper.update(dish);
    }

    @Override
    public DishDTO getById(Long id) {
        return dishMapper.getById(id);
    }

    @Override
    public void startOrStop(Integer status, Long id) {
        Dish dish = new Dish();
        dish.setId(id);
        dish.setStatus(status);
        dishMapper.update(dish);
    }

    @Override
    public void delete(List<Long> ids) {
        for (Long id : ids) {
            Integer status = dishMapper.getById(id).getStatus();
            if (Objects.equals(status, StatusConstant.ENABLE)) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }

            Integer count = setmealDishMapper.countByDishId(id);
            if (count > 0) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }
        }

        dishMapper.delete(ids);
    }

    @Override
    public List<DishDTO> list(Long categoryId) {
        return dishMapper.list(categoryId);
    }
}
